package com.sunseagear.wind.modules.email.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunseagear.common.base.http.R;
import com.sunseagear.common.base.http.RPage;
import com.sunseagear.common.base.mvc.controller.BaseBeanController;
import com.sunseagear.common.utils.ObjectUtils;
import com.sunseagear.wind.common.aspectj.annotation.Log;
import com.sunseagear.wind.common.aspectj.enums.LogType;
import com.sunseagear.wind.modules.email.entity.EmailSendLog;
import com.sunseagear.wind.modules.email.entity.query.EmailSendLogQuery;
import com.sunseagear.wind.modules.email.service.IEmailSendLogService;
import com.sunseagear.wind.modules.email.service.IEmailSendService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 *
 * @version V1.0
 * @package com.sunseagear.wind.modules.email.controller
 * @title: 邮件发送日志控制器
 * @description: 邮件发送日志控制器 * @date: 2018-09-12 10:58:46
 * @copyright: 2018 www.sunseagear.com Inc. All rights reserved.
 */

@RestController
@RequestMapping("/email/sendlog")
@Log(title = "邮件发送日志")
@RequiredArgsConstructor
public class EmailSendLogController extends BaseBeanController {

    private final IEmailSendLogService emailSendLogService;
    private final IEmailSendService emailSendService;


    @GetMapping(value = "list")
    @Log(logType = LogType.SELECT)
    @SaCheckPermission("email:sendlog:list")
    public RPage<EmailSendLog> list(EmailSendLogQuery query) {
        //加入条件
        QueryWrapper<EmailSendLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(EmailSendLog::getResponseDate)
                .like(ObjectUtils.isNotEmpty(query.getEmail()),EmailSendLog::getEmail, query.getEmail())
                .like(ObjectUtils.isNotEmpty(query.getSubject()),EmailSendLog::getSubject, query.getSubject())
                .eq(ObjectUtils.isNotEmpty(query.getStatus()),EmailSendLog::getStatus, query.getStatus());
        // 预处理
        Page<EmailSendLog> pageBean = emailSendLogService.page(getPage(), queryWrapper);
        return RPage.success(pageBean);
    }

    @DeleteMapping("delete")
    @Log(logType = LogType.DELETE)
    @SaCheckPermission("email:sendlog:delete")
    public R<Void> delete(@RequestBody List<Long> ids) {
        emailSendLogService.removeBatchByIds(ids);
        return R.success("删除成功");
    }

    @PostMapping(value = "retrySend")
    @Log(logType = LogType.SELECT)
    @SaCheckPermission("email:sendlog:list")
    public R<Void> retrySend(@RequestBody List<Long> ids) {
        try {
            emailSendService.retrySend(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("重发队列添加失败");
        }
        return R.success("重发队列添加成功");
    }
}
